<template>
    <view class="promote-goods">
        <scroll-view :scroll-y="true" scroll-top="scrollTop" v-if="list?.length" class="goods-list">
            <view v-for="(item, index) in list" :key="index" class="list-item" @tap="jumpGoodsPage(item)">
                <view class="common">
                    <GoodsImgStatus fontSize="22rpx" width="91rpx" lineWidth="69rpx" v-if="item.onSale == 3" />
                    <image
                        class="goods-img"
                        :src="item.coverSrc || defaultImg"
                        :lazy-load="true"
                        :draggable="false"></image>
                </view>
                <view class="goods-content">
                    <text class="title">{{ item.goodsName }}</text>
                    <view class="content-bottom">
                        <view class="price-point">
                            <view class="price"
                                >￥<text class="bold">{{ priceNum(item.price, 0) }}</text>
                                <text v-if="priceNum(item.price, 1)">.{{ priceNum(item.price, 1) }}</text
                                ><text v-if="item.isTextVisible">起</text></view
                            >
                            <view>
                                <view class="points">
                                    <view class="points-icon">赚</view>
                                    <text>
                                        {{ item.benefitMode == 2 ? '￥' : '' }}{{ item.commission
                                        }}{{ item.benefitMode == 1 ? '积分' : '' }}
                                    </text>
                                </view>
                            </view>
                        </view>
                        <button @tap.stop="handleSharePopup(item)" class="share-btn">分享</button>
                    </view>
                </view>
            </view>
            <view class="list-loading">
                {{ isBottom ? (listLoading ? '加载中…' : '已经到底啦！') : '' }}
            </view>
        </scroll-view>
        <view class="no-data" v-if="!list?.length">
            <img class="no-data-img" :src="getImgOssUrl('/ui-prod-2.0.0/nodata_1.1.png')" />
            <text class="no-data-title">未配置相关商品</text>
        </view>
        <SharePopup
            ref="sharePopupRef"
            :shareAppMessage="shareAppMessage"
            :slotViews="slotViews"
            :pageInfo="{ pageTitle: '商品', linkPrefix: `【${currentGoods?.goodsName}】` }"
            v-bind="$attrs">
            <template v-slot:context>
                <view class="share-promote-price-title">{{ currentGoods.goodsName }}</view>
                <view class="share-promote-price"
                    >￥<text class="share-promote-price-bold">{{ priceNum(currentGoods.price, 0) }}</text>
                    <text v-if="priceNum(currentGoods.price, 1)">.{{ priceNum(currentGoods.price, 1) }}</text
                    ><text v-if="currentGoods.isTextVisible">起</text></view
                >
            </template>
        </SharePopup>
        <!-- 隐私监听 -->
        <el-privacy-listener-popup></el-privacy-listener-popup>
    </view>
</template>

<script setup>
import { watch, ref, computed, reactive, onMounted } from 'vue';
import { onShow, onReachBottom, onPageScroll } from '@dcloudio/uni-app';
import router from '@/router';
import request from '@/request';
import { onShareAppMessage } from '@dcloudio/uni-app';
import storage from '@/commons/storage';
import SharePopup from '@/components/sharePopup';
import GoodsImgStatus from '@/components/goodsImgStatus';

import { floatDivide, getImgOssUrl } from '@/commons/utils';

const defaultImg = ref(getImgOssUrl('/ui-prod-2.0.0/errorImg.png'));

let list = reactive([]);
let Data = reactive({
    beforeShopId: null,
    scrollTop: 0,
    totalCount: 0
});
let form = reactive({
    page: 1,
    perPage: 10
});
let listLoading = ref(false);
const slotViews = height => [
    {
        type: 'text',
        content: currentGoods.goodsName,
        fontSize: 16,
        lineHeight: 22,
        color: '#333333',
        textAlign: 'left',
        top: height + 52,
        left: 15,
        width: 220,
        MaxLineNumber: 2,
        breakWord: true
    },
    {
        type: 'text',
        content: `￥${priceNum(currentGoods.price, 0)}${
            priceNum(currentGoods.price, 1) ? '.' + priceNum(currentGoods.price, 1) : ''
        }${currentGoods.isTextVisible ? '起' : ''}`,
        fontSize: 20,
        lineHeight: 14,
        color: '#FE292B',
        textAlign: 'left',
        top: height + 100,
        left: 15,
        MaxLineNumber: 1,
        breakWord: true
    }
];

const priceNum = (amount, index) => {
    let price = floatDivide(amount, 100);
    let list = [];
    try {
        list = price.toString().split('.');
    } catch (e) {
        list = [Number(price)];
    }
    return list[index];
};

const jumpGoodsPage = ({ goodsNo, goodId: goodsId, shopId }) => {
    Data.beforeShopId = storage.get('ZW_SHOP_ID');
    router.push({
        path: '/pages-cart/good/index',
        query: {
            goodsNo,
            goodsId,
            // inviteMemberId: storage.get('userId'),
            // channel: 2,
            shopId
        }
    });
};

const getList = async () => {
    // todo:活动中的页面
    listLoading.value = true;
    const { data } = await request('plugLists', form);
    Data.totalCount = data?.totalCount || 0;
    listLoading.value = false;
    if (form.page === 1) {
        list.length = 0;
    }
    list.push(
        ...(data?.list || []).map(item => {
            item.commission = (item.commission != null ? item.commission / 100 : '') + '';
            item.commission = item.commission.length > 7 ? `${item.commission.slice(0, 7)}...` : item.commission;
            // 价格多个选最小的起
            item.price = item.goodsMinPrice || 0;
            item.isTextVisible = item.goodsMinPrice && item.goodsMaxPrice && item.goodsMinPrice !== item.goodsMaxPrice;
            return item;
        })
    );
};

const isBottom = computed(() => {
    return Data.scrollTop > 50;
});
onPageScroll(e => {
    Data.scrollTop = e.scrollTop;
});
// 上拉加载
onReachBottom(() => {
    if (Data.totalCount === list.length) {
        return;
    }
    form.page++;
    getList();
});

// onMounted(() => {
//     getList();
// });
onShow(() => {
    userId.value = storage.get('userId');
    Data.beforeShopId && storage.set('ZW_SHOP_ID', Data.beforeShopId);
    if (!Data.totalCount) {
        getList();
    }
});

// 分享邀请
const sharePopupRef = ref();
let currentGoods = reactive({});
let userId = ref(storage.get('userId'));
const shareAppMessage = computed(() => {
    const { coverSrc, goodsName, goodId: goodsId, goodsNo, shopId } = currentGoods || {};
    // todo:活动中的页面，以及邀请人的id
    let data = {
        title: goodsName,
        path: `/pages-cart/good/index?goodsId=${goodsId}&goodsNo=${goodsNo}&shopId=${shopId}&inviteMemberId=${userId.value}&channel=2`,
        imageUrl: coverSrc || defaultImg.value
    };
    return data;
});
const handleSharePopup = res => {
    Object.assign(currentGoods, res);
    sharePopupRef?.value?.handlePopup();
};
// onShareAppMessage(res => {
//     // const shopId = storage.get('ZW_SHOP_ID');
//     const { coverSrc, goodsName, goodId: goodsId, goodsNo, shopId } = res.target.dataset.item;
//     // todo:活动中的页面，以及邀请人的id
//     let data = {
//         title: `${goodsName}`,
//         path: `/pages-cart/good/index?goodsId=${goodsId}&goodsNo=${goodsNo}&shopId=${shopId}&inviteMemberId=${storage.get(
//             'userId'
//         )}&channel=2`,
//         imageUrl: coverSrc || defaultImg.value
//     };
//     return data;
// });
</script>

<style lang="scss" scoped src="./index.scss"></style>
